package com.gitee.xhs.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author BigHead
 * @date 2022/7/1 16:28
 * @description StringTemplateUtil
 */
public class StringTemplateUtil {

    private static final Logger logger = LoggerFactory.getLogger(StringTemplateUtil.class);

    public static final String DEF_REGEX = "\\$\\{(.+?)\\}";

    public static String render(String template, Map<String, String> data) {
        return render(template, data, DEF_REGEX);
    }

    public static String render(String template, Map<String, String> data, String regex) {
        if (template == null || template.trim().isEmpty()) {
            return "";
        }

        if (regex == null || regex.trim().isEmpty()) {
            return template;
        }

        if (data == null || data.size() == 0) {
            return template;
        }

        try {
            StringBuffer appendReplaceSb = new StringBuffer();
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(template);

            while (matcher.find()) {
                //当前第一个子分组正则匹配的字符串
                String key = matcher.group(1);
                String value = data.get(key);

                /*Matcher. appendReplacement：将当前匹配的子字符串替换为指定的字符串，并且将替换后的字符串
                及其之前到上次匹配的子字符串之后的字符串添加到一个StringBuffer对象中。*/
                matcher.appendReplacement(appendReplaceSb, value);
            }

            /*   Matcher. appendTail：将最后一次匹配之后的字符串添加到一个StringBuffer对象中。*/
            matcher.appendTail(appendReplaceSb);
            return appendReplaceSb.toString();
        } catch (Exception e) {
            logger.error("", e);
        }
        return template;
    }

}
